package com.uwo.commons.kits;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * gzip压缩工具类
 * @author hao.yan
 */
public class GzipKits {

    /**
     * 压缩
     * @param in
     * @throws IOException
     */
    public static ByteArrayOutputStream compress(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        int count;
        byte data[] = new byte[1024];
        while ((count = in.read(data, 0, 1024)) != -1) {
            gzip.write(data, 0, count);
        }
        gzip.finish();
        gzip.close();
        return out;
    }

    public static byte[] compressToBytes(InputStream in) throws IOException {
        return compress(in).toByteArray();
    }

    /**
     * 压缩
     */
    public static byte[] compress(byte[] bytes) throws IOException {
        ByteArrayOutputStream out = compress(new ByteArrayInputStream(bytes));
        return out.toByteArray();
    }

    /**
     * 解压
     * @param bytes
     */
    public static byte[] decompress(byte[] bytes) throws IOException {
        return decompressToBytes(new ByteArrayInputStream(bytes));
    }

    /**
     * 解压
     * @param in
     */
    public static ByteArrayOutputStream decompress(InputStream in) throws IOException{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPInputStream gzip = new GZIPInputStream(in);
        byte[] buffer = new byte[1024];
        int n;
        while ((n = gzip.read(buffer))>= 0) {
            out.write(buffer, 0, n);
        }
        return out;
    }

    public static byte[] decompressToBytes(InputStream in) throws IOException{
        return decompress(in).toByteArray();
    }

}
